/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.boot.web.reactive.error;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;

import com.iiifi.kite.core.result.Result;
import com.iiifi.kite.core.result.SystemCode;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * webflux 异常处理
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
public class KiteErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {

    public KiteErrorWebExceptionHandler(ErrorAttributes attributes, ResourceProperties properties,
            ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(attributes, properties, errorProperties, applicationContext);
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * Render the error information as a JSON payload.
     *
     * @param request the current request
     * @return a {@code Publisher} of the HTTP response
     */
    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Throwable error = this.getError(request);
        HttpStatus status = determineHttpStatus(error);
        // 返回消息
        String message = status.value() + ":" + status.getReasonPhrase();
        Result<Object> result = Result.fail(SystemCode.FAILURE, message);
        return ServerResponse.status(status)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(result));
    }

    private HttpStatus determineHttpStatus(Throwable error) {
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getStatus();
        } else {
            ResponseStatus responseStatus =
                    AnnotatedElementUtils.findMergedAnnotation(error.getClass(), ResponseStatus.class);
            return responseStatus != null ? responseStatus.code() : HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

}
